package com.sunchangpeng.wechat.core.token;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;

import java.util.concurrent.atomic.AtomicBoolean;

@Data
public class AccessToken {
    @JSONField(name = "access_token")
    private String accessToken;

    @JSONField(name = "expires_in")
    private long expiresIn;

    private long expiresTill;

    private AtomicBoolean expired = new AtomicBoolean(false);

    public void setExpiresIn(long expiresIn) {
        this.expiresIn = expiresIn;
        this.expiresTill = System.currentTimeMillis() + (expiresIn * 1000) - 300000;
    }

    public void expireToken() {
        this.expired.compareAndSet(false, true);
    }

    public boolean expired() {
        return expired.get() || System.currentTimeMillis() > expiresTill;
    }

    public static AccessToken fromJson(String json) {
        return JSON.parseObject(json, AccessToken.class);
    }
}
